﻿using Application.Common.Interfaces;
using FluentValidation;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Organizations.Commands.Add;

/// <summary>
/// 校验添加组织机构信息
/// </summary>
public class AddOrganizationCommandValidator : AbstractValidator<AddOrganizationCommand>
{
    private readonly IApplicationDbContext _context;
    public AddOrganizationCommandValidator(IApplicationDbContext context)
    {
        _context = context;

        RuleFor(x => x.OrganizationName)
            .NotNull().WithMessage("组织机构名称不能为空！")
            .MustAsync(OrganizationNameExistsAsync).WithMessage("组织机构名称重复！");

        RuleFor(x => x.ParentId).MustAsync(ValidParentIdAsync).WithMessage("非法数据！");
        //RuleFor(x => x.OrganizationPrincipalId).MustAsync(OrganizationPrincipalExistsAsync).WithMessage("非法数据！");
    }

    /// <summary>
    /// 组织机构是否合法
    /// </summary>
    /// <param name="parentId"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    private async Task<bool> ValidParentIdAsync(long? parentId, CancellationToken cancellationToken)
    {
        if (parentId == null)
            return true;

        return await _context.Organizations.AnyAsync(x => x.Id == parentId, cancellationToken);
    }

    ///// <summary>
    ///// 组织机构负责人是否存在
    ///// </summary>
    ///// <param name="OrganizationPrincipalId"></param>
    ///// <param name="cancellationToken"></param>
    ///// <returns></returns>
    //private async Task<bool> OrganizationPrincipalExistsAsync(long? OrganizationPrincipalId, CancellationToken cancellationToken)
    //{
    //    if (OrganizationPrincipalId == null) return true;

    //    return await _context.Users.AnyAsync(x => x.Id == OrganizationPrincipalId, cancellationToken);
    //}

    /// <summary>
    /// 校验组织机构名称重复
    /// </summary>
    /// <param name="OrganizationName"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    private async Task<bool> OrganizationNameExistsAsync(string? OrganizationName, CancellationToken cancellationToken)
    {
        return !(await _context.Organizations.AnyAsync(x => x.OrganizationName == OrganizationName, cancellationToken));
    }
}